<template>
  <div class="blog-page">
    <SearchBar :placeholder="searchPlaceholder" />
    
    <CategoryList 
      :categories="categories" 
      :default-active="activeCategory"
      @change="onCategoryChange" 
    />
    
    <div class="blog-list-container">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div class="blog-list">
            <BlogItem 
              v-for="(blog, index) in blogs" 
              :key="blog.id" 
              :data="blog" 
              @click="goToBlogDetail(blog.id)" 
            />
          </div>
        </van-list>
      </van-pull-refresh>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import SearchBar from '../../components/common/SearchBar.vue'
import CategoryList from '../../components/blog/CategoryList.vue'
import BlogItem from '../../components/blog/BlogItem.vue'

const router = useRouter()
const route = useRoute()

// 搜索框占位符
const searchPlaceholder = ref('搜索博客')

// 分类数据
const categories = ref([
  { id: 'all', name: '全部', count: 0 },
  { id: 'tech', name: '技术', count: 0 },
  { id: 'design', name: '设计', count: 0 },
  { id: 'product', name: '产品', count: 0 },
  { id: 'operation', name: '运营', count: 0 },
  { id: 'career', name: '职场', count: 0 },
  { id: 'life', name: '生活', count: 0 }
])

// 当前选中的分类
const activeCategory = ref(route.query.category || 'all')

// 博客列表数据
const blogs = ref([])
const page = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)

// 加载博客数据
const loadBlogs = async (isRefresh = false) => {
  if (isRefresh) {
    page.value = 1
    blogs.value = []
    finished.value = false
  }
  
  try {
    // 实际项目中应该调用真实的API
    // const { data } = await get('/api/blogs', {
    //   page: page.value,
    //   pageSize: pageSize.value,
    //   category: activeCategory.value !== 'all' ? activeCategory.value : undefined,
    //   keyword: route.query.q
    // })
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const mockData = Array(pageSize.value).fill(0).map((_, index) => ({
      id: `${page.value}-${index}`,
      title: `博客标题 ${page.value}-${index}`,
      summary: '这是一篇博客的摘要，介绍了一些有趣的内容和技术分享。这是一篇博客的摘要，介绍了一些有趣的内容和技术分享。',
      author: {
        id: 'user1',
        name: '张三',
        avatar: 'https://picsum.photos/id/1001/100/100'
      },
      views: Math.floor(Math.random() * 2000),
      likes: Math.floor(Math.random() * 500),
      createTime: new Date().toISOString(),
      cover: index % 3 === 0 ? `https://picsum.photos/id/${(page.value * 10) + index}/200/120` : undefined
    }))
    
    if (isRefresh) {
      blogs.value = mockData
    } else {
      blogs.value.push(...mockData)
    }
    
    // 更新分类数量
    categories.value = categories.value.map(category => ({
      ...category,
      count: Math.floor(Math.random() * 100)
    }))
    
    // 判断是否加载完成
    if (page.value >= 3) {
      finished.value = true
    }
    
    page.value++
  } catch (error) {
    console.error('加载博客失败:', error)
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 下拉刷新
const onRefresh = () => {
  loadBlogs(true)
}

// 上拉加载更多
const onLoad = () => {
  loadBlogs()
}

// 分类变化
const onCategoryChange = (category) => {
  activeCategory.value = category.id
  router.replace({ query: { ...route.query, category: category.id } })
  loadBlogs(true)
}

// 跳转到博客详情
const goToBlogDetail = (id) => {
  router.push(`/blog/${id}`)
}

onMounted(() => {
  loadBlogs()
})
</script>

<style lang="scss" scoped>
.blog-page {
  min-height: 100vh;
  background-color: var(--background-color);
  
  .blog-list-container {
    padding: 12px;
    
    .blog-list {
      display: flex;
      flex-direction: column;
      gap: 12px;
    }
  }
}
</style> 